<!DOCTYPE html>
<html>

<head>
    <!-- 页面meta -->
    <meta charset="utf-8">
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <title>商品编辑</title>
    <!-- Tell the browser to be responsive to screen width -->
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">

    <link rel="stylesheet" href="/plugins/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/AdminLTE.css">
    <link rel="stylesheet" href="/plugins/adminLTE/css/skins/_all-skins.min.css">
    <link rel="stylesheet" href="/css/style.css">
    <script src="/plugins/jQuery/jquery-2.2.3.min.js"></script>
    <script src="/plugins/bootstrap/js/bootstrap.min.js"></script>

    <!-- 富文本编辑器 -->
    <link rel="stylesheet" href="/plugins/kindeditor/themes/default/default.css"/>
    <script charset="utf-8" src="/plugins/kindeditor/kindeditor-min.js"></script>
    <script charset="utf-8" src="/plugins/kindeditor/lang/zh_CN.js"></script>

    <link rel="stylesheet" href="/plugins/select2/select2.css"/>
    <link rel="stylesheet" href="/plugins/select2/select2-bootstrap.css"/>
    <script src="/plugins/select2/select2.min.js" type="text/javascript"></script>

    <!--	<%&#45;&#45;bootstrap-fileinput&#45;&#45;%>-->
    <script type="text/javascript" src="/js/bootstrap-fileinput/js/fileinput.js"></script>
    <script type="text/javascript" src="/js/bootstrap-fileinput/js/locales/zh.js"></script>
    <link rel="stylesheet" type="text/css" href="/js/bootstrap-fileinput/css/fileinput.min.css"/>


</head>

<body class="hold-transition skin-red sidebar-mini">
<script>
    function addAll() {
        editor.sync();
        var list = []
        var text1 = $("[name=text]");
        var value1 = $("[name=value]");
        for (var i = 0; i < text1.length; i++) {
            var listOne = {text: $(text1[i]).text(), value: $(value1[i]).val()};
            list.push(listOne);
        }
        var list1 = [];
        var url = $("[name=url]");
        var color = $("[name=color]");
        for (var i = 0; i < url.length; i++) {
            var itemImages = {color: $(color[i]).val(), url: $(url[i]).val()};
            list1.push(itemImages);
        }
        var customAttributeItems = JSON.stringify(list);
        var itemImages1 = JSON.stringify(list1);
        //转换为字符串
        var addArr = []

        var s1 = ""

        var s2 = ""

        var pros = $("#dataType1").find("tr")

        for (var i = 1; i < pros.length; i++) {

            var tds = $(pros[i]).find("td")

            if (tds.length == 6) {

                var v1 = $(tds[0]).text()

                var v2 = $(tds[1]).text()

                var p = $(tds[2]).find("input")

                var price = $(p).val()

                var stt = $("#goodsName").val() + v1 + v2

                var so = $(tds[3]).find("input")

                var socketCount = $(so).val()

                var ic = $(tds[4]).find("input")

                var icv = $(ic).val()

                var ths = $(pros[0]).find("th")

                var thp1 = $(ths[0]).text()

                var thp2 = $(ths[1]).text()

                s1 = thp1

                s2 = thp2

                var spec = {'thp1': v1, 'thp2': v2}

                var st = {
                    title: stt,
                    price: price,
                    stockCount: socketCount,
                    categoryid: $("#s3").val(),
                    status: 1,
                    createTime: new Date().getTime(),
                    isDefault: 1,
                    category: $("#s3").find("option:selected").text(),
                    brand: $("#brand").find("option:selected").text(),
                    spec: spec,
                    num: 10,
                    updateTime: new Date().getTime(),
                    image: $("#photo").val()
                }

                addArr.push(st)

            } else {

                var v1 = $(tds[0]).text()

                var p = $(tds[1]).find("input")

                var price = $(p).val()

                var so = $(tds[2]).find("input")

                var socketCount = $(so).val()

                var ic = $(tds[3]).find("input")

                var icv = $(ic).val()

                var ths = $(pros[0]).find("th")

                var thp1 = $(ths[0]).text()

                s1 = thp1

                var spec = {thp1: v1}

                var st = {
                    title: $("#goodsName").val() + v1,
                    price: price,
                    stockCount: socketCount,
                    categoryid: $("#s3").val(),
                    status: 1,
                    createTime: new Date().getTime(),
                    isDefault: 1,
                    category: $("#s3").find("option:selected").text(),
                    brand: $("#brand").find("option:selected").text(),
                    spec: spec,
                    num: 10,
                    updateTime: new Date().getTime(),
                    image: $("#photo").val()
                }

                addArr.push(st)
            }


        }
        var propertys = JSON.stringify(addArr)
        var specificationItems = JSON.stringify(items)

        $.ajax({
            url: "/goods/addAllInfo",
            type: "post", //请求方式 get post 默认get
            data: {

                category1Id: $("#s1").val(),

                category2Id: $("#s2").val(),

                category3Id: $("#s3").val(),

                goodsName: $("#goodsName").val(),

                caption: $("#caption").val(),

                price: $("#price").val(),

                introduction: $("#introduction").val(),

                packageList: $("#packageList").val(),

                saleService: $("#saleService").val(),

                typeTemplateId: $("#span").val(),

                brandId: $("#brand").val(),

                itemImages: itemImages1,

                customAttributeItems: customAttributeItems,

                propertys: propertys,

                specificationItems: specificationItems,

                thp1: s1,

                thp2: s2,
            },
            traditional: true,
            dataType: "json", //返回值类型 html json text xml
            async: true,//true代表异步请求 false代表同步请求
            success: function (result) {//成功回调函数
                if (result.code == 10000) {
                    alert("增加成功")
                }
            },
            error: function (i) {//发生错误回调函数
                alert("异常错误")
            }

        })
    }
</script>
<form id="formId">
    <!-- 正文区域 -->
    <section class="content">

        <div class="box-body">

            <!--tab页-->
            <div class="nav-tabs-custom">

                <!--tab头-->
                <ul class="nav nav-tabs">
                    <li class="active">
                        <a data-toggle="tab" href="#home">商品基本信息</a>
                    </li>
                    <li>
                        <a data-toggle="tab" href="#pic_upload">商品图片</a>
                    </li>
                    <li>
                        <a data-toggle="tab" href="#customAttribute" onclick="showKuo()">扩展属性</a>
                    </li>
                    <li>
                        <a data-toggle="tab" href="#spec">规格</a>
                    </li>
                </ul>
                <!--tab头/-->
                <script>
                    var count = 1;

                    function showItemCat(parentId) {
                        if (count < 3) {
                            count += 1;
                            $.ajax({
                                url: "/specification/getTbItemCat/" + parentId,
                                type: "get", //请求方式 get post 默认get
                                dataType: "json", //返回值类型 html json text xml
                                async: true,//true代表异步请求 false代表同步请求
                                success: function (result) {//成功回调函数

                                    var page = result.data;

                                    var div = "";
                                    if (count == 2) {
                                        div += '<option value="-1" selected hidden disabled >--请选择</option>';
                                        for (var i = 0; i < page.length; i++) {
                                            div += '<option value="' + page[i].id + '" >' + page[i].name + '</option>';
                                        }
                                        $("#s2").html(div);
                                    } else if (count == 3) {
                                        div += '<option value="-1" selected hidden disabled >--请选择</option>';
                                        for (var i = 0; i < page.length; i++) {
                                            div += '<option value="' + page[i].id + '" >' + page[i].name + '</option>';
                                        }
                                        $("#s3").html(div);
                                    }
                                },
                                error: function (i) {//发生错误回调函数
                                    alert("异常错误")
                                }

                            })
                        } else {
                            $.ajax({
                                url: "/specification/showTypeId/" + parentId,
                                type: "get", //请求方式 get post 默认get
                                dataType: "json", //返回值类型 html json text xml
                                async: true,//true代表异步请求 false代表同步请求
                                success: function (result) {//成功回调函数
                                    var page = result.data;
                                    $("#span").val(page.typeId);
                                },
                                error: function (i) {//发生错误回调函数
                                    alert("异常错误")
                                }

                            })
                        }
                    }

                    function brandShow() {
                        $.ajax({
                            url: "/specification/getBrand/" + $("#span").val(),
                            type: "get", //请求方式 get post 默认get
                            dataType: "json", //返回值类型 html json text xml
                            async: true,//true代表异步请求 false代表同步请求
                            success: function (result) {//成功回调函数
                                var page = result.data;
                                var brandStr = page.brandIds;
                                var brandJSON = JSON.parse(brandStr);
                                div = "";
                                div += '<option value="-1" selected hidden disabled>--请选择--</option>';
                                for (var i = 0; i < brandJSON.length; i++) {
                                    div += '<option value="' + brandJSON[i].id + '">' + brandJSON[i].text + '</option>';
                                }
                                $("#brand").html(div);
                            },
                            error: function (i) {//发生错误回调函数
                                alert("异常错误")
                            }

                        })
                    }
                </script>
                <!--tab内容-->
                <div class="tab-content">
                    <!--表单内容-->
                    <div class="tab-pane active" id="home">
                        <div class="row data-type">
                            <div class="col-md-2 title">商品分类</div>

                            <div class="col-md-10 data">
                                <table>
                                    <tr>
                                        <td>
                                            <select id="s1" name="category" class="form-control"
                                                    onchange="showItemCat(this.value)">
                                                <option disabled hidden selected value="-1">--请选择</option>
                                                <option th:each="spec : ${tbItemCatList}" th:value="${spec.id}">
                                                    [[${spec.name}]]
                                                </option>
                                            </select>
                                        </td>
                                        <td>
                                            <select name="category" id="s2" class="form-control select-sm"
                                                    onchange="showItemCat(this.value)">

                                            </select>
                                        </td>
                                        <td>
                                            <select name="category" id="s3" class="form-control select-sm"
                                                    onchange="showItemCat(this.value)">

                                            </select>
                                        </td>
                                        <td>
                                            模板ID:<input disabled="disabled" id="span" name="typeId" type="text">
                                        </td>
                                    </tr>
                                </table>

                            </div>
                            <div class="col-md-2 title">商品名称</div>
                            <div class="col-md-10 data">
                                <input class="form-control" placeholder="商品名称" id="goodsName" type="text"
                                       name="goodsName" value=""
                                       onclick="brandShow()">
                            </div>

                            <div class="col-md-2 title">品牌</div>
                            <div class="col-md-10 data">
                                <select class="form-control" id="brand" name="brandId">

                                </select>
                            </div>

                            <div class="col-md-2 title">副标题</div>
                            <div class="col-md-10 data">
                                <input class="form-control" id="caption" name="caption" placeholder="副标题" type="text">
                            </div>

                            <div class="col-md-2 title">价格</div>
                            <div class="col-md-10 data">
                                <div class="input-group">
                                    <span class="input-group-addon">¥</span>
                                    <input class="form-control" name="price" id="price" placeholder="价格" type="text"
                                           value="">
                                </div>
                            </div>

                            <div class="col-md-2 title editer">商品介绍</div>
                            <div class="col-md-10 data editer">
                                <textarea id="introduction" name="introduction"
                                          style="width:800px;height:400px;visibility:hidden;"></textarea>
                            </div>

                            <div class="col-md-2 title rowHeight2x">包装列表</div>
                            <div class="col-md-10 data rowHeight2x">

                                <textarea class="form-control" id="packageList" name="packageList" placeholder="包装列表"
                                          rows="4"></textarea>
                            </div>

                            <div class="col-md-2 title rowHeight2x">售后服务</div>
                            <div class="col-md-10 data rowHeight2x">
                                <textarea class="form-control" id="saleService" name="saleService" placeholder="售后服务"
                                          rows="4"></textarea>
                            </div>
                        </div>
                    </div>
                    <!--图片上传-->
                    <div class="tab-pane" id="pic_upload">
                        <div class="row data-type">
                            <!-- 颜色图片 -->
                            <div class="btn-group">
                                <button class="btn btn-default" data-target="#uploadModal" data-toggle="modal" title="新建" type="button"><i class="fa fa-file-o"></i> 新建</button>

                            </div>

                            <table class="table table-bordered table-striped table-hover dataTable">
                                <thead>
                                <tr>

                                    <th class="sorting">颜色</th>
                                    <th class="sorting">图片</th>
                                    <th class="sorting">操作</th>
                                </thead>
                                <tbody id="tbody">

                                </tbody>
                            </table>

                        </div>
                    </div>
                    <script>
                        function deleteOneTr1(obj) { //删除当前行(这里我就不写 script 这个格式了)
                            var a = document.getElementById("tbody"); //一样 需要找到 表格的父类
                            var a1 = obj.parentNode.parentNode;  // 找到需要删除的位置 ，当按钮触发时直接传入自己进来 这样就拿到了位置
                            a.removeChild(a1);  // 直接 remove 这个子类
                        }

                        function showKuo() {
                            if ($("#span").val() != '' && $("#span").val() != null) {
                                $.ajax({
                                    url: "/specification/getBrand/" + $("#span").val(),
                                    type: "get", //请求方式 get post 默认get
                                    dataType: "json", //返回值类型 html json text xml
                                    async: true,//true代表异步请求 false代表同步请求
                                    success: function (result) {//成功回调函数
                                        var page = result.data;
                                        console.log(page)
                                        var customAttributeItemsStr = page.customAttributeItems;
                                        var customAttributeItemsJSON = JSON.parse(customAttributeItemsStr);
                                        div = "";
                                        div += '<div className="row data-type">';
                                        for (var i = 0; i < customAttributeItemsJSON.length; i++) {

                                            div += '<div><div name ="text" className="col-md-2 title">' + (i + 1) + ':' + customAttributeItemsJSON[i].text + '</div>';
                                            div += '<div className="col-md-10 data">';
                                            div += '<input className="form-control" id="value" name="value" placeholder="扩展属性value值' + (i + 1) + '">';
                                            div += '</div>';
                                            div += '</div>';
                                        }
                                        div += '</div>';
                                        $("#customAttribute").html(div);
                                    },
                                    error: function (i) {//发生错误回调函数
                                        alert("异常错误")
                                    }
                                })
                            }
                        }
                    </script>


                    <!--扩展属性-->
                    <div class="tab-pane" id="customAttribute">

                    </div>

                    <script>
                        function specification() {
                            if ($("#check").prop("checked")) {
                                $.ajax({
                                    url: "/goods/getTemplateById",
                                    data: {typeId: $("#span").val()},
                                    dataType: "json",
                                    type: "post",
                                    success: function (result) {
                                        var page = result.data.specVOList;
                                        console.log(page)
                                        div = '';
                                        for (var i = 0; i < page.length; i++) {
                                            var page1 = page[i].optionList;

                                            div += '<div name="specificationName" >'

                                            div += '<div class="col-md-2 title">' + page[i].spec.specName + '</div>'

                                            div += '<div class="col-md-10 data">'

                                            for (var j = 0; j < page1.length; j++) {

                                                div += '<span><input type = "checkbox" onclick = "checkSpec(this)" value="' + page1[j].optionName.id + '">' + page1[j].optionName + '</span>'
                                            }

                                            div += '</div>'

                                            div += '</div>'
                                        }
                                        $("#dataType").html(div);
                                    },
                                    error: function (data) {
                                        alert("error");
                                    }
                                })
                            } else {
                                $("#dataType").html("");
                                $("#dataType1").html("");

                            }
                        }

                        var items = [];

                        //勾选规格选项复选框函数
                        function checkSpec(event) {

                            var span = event.parentNode

                            var value = $(span).text()

                            var div1 = span.parentNode

                            var div2 = div1.previousSibling

                            var name = $(div2).text()
                            //调用方法判断原集合中是否已有attributeName
                            var obj = searchObjectByKey(items, 'attributeName', name);
                            if (obj != null) {
                                if ($(event).prop('checked')) {//勾选
                                    //如果之前有数据，往原有的对象中追加
                                    obj.attributeValue.push(value);
                                } else {//取消勾选
                                    obj.attributeValue.splice(obj.attributeValue.indexOf(value), 1)//从items中移除规格选项
                                    //如果规格选项没有数据了
                                    if (obj.attributeValue.length == 0) {
                                        //移除items中的数据
                                        items.splice(items.indexOf(obj), 1)
                                    }
                                }
                            } else {
                                //如果之前没有数据，items新加数据
                                items.push({'attributeName': name, 'attributeValue': [value]});
                            }
                            //console.log(items);
                            //后续调用，这里先不调用，后续选择之后组装选择后的数据用的
                            var tem = createItemList();

                            createTable(tem)

                        }

                        //遍历组装用户勾选规格选项数据
                        function searchObjectByKey(list, attributeName, attributeValue) {
                            for (var i = 0; i < list.length; i++) {
                                //如果list中我们选择key存在
                                if (list[i][attributeName] == attributeValue) {
                                    return list[i];//返回当前对象
                                }
                            }
                            //遍历结束后都不存在，返回null
                            return null;
                        }

                        //创建SKU列表
                        function createItemList() {
                            //创建初始值
                            var itemList = [{att: {}}];
                            for (var i = 0; i < items.length; i++) {
                                itemList = addColum(itemList, items[i].attributeName, items[i].attributeValue);
                            }

                            return itemList;
                        }

                        //添加表格的列
                        function addColum(list, columName, columValues) {
                            //定义新集合接收行
                            var newList = [];
                            for (var i = 0; i < list.length; i++) {
                                var oldRow = list[i];
                                for (var j = 0; j < columValues.length; j++) {
                                    var newRow = JSON.parse(JSON.stringify(oldRow)); //深克隆
                                    newRow.att[columName] = columValues[j];
                                    newList.push(newRow)
                                }
                            }
                            return newList;
                        }

                        function createTable(obj) {

                            var a = JSON.stringify(obj)

                            var arr = JSON.parse(a)

                            var b = JSON.stringify(arr[0].att)

                            var d = b.substring(1, (b.length - 1))

                            var e = d.split(":")

                            var tr = ""

                            tr += '<tr>'

                            for (var i = 0; i < e.length; i++) {

                                if (i == 1) {

                                    var ee = e[i].split(",")

                                    for (var j = 1; j < ee.length; j++) {

                                        tr += '<th class="sorting" id = "p">' + JSON.parse(ee[j]) + '</th>'

                                    }

                                }

                                if (i == 0) {

                                    tr += '<th class="sorting" id = "p">' + JSON.parse(e[i]) + '</th>'
                                }

                            }

                            tr += '<th class="sorting">价格</th>'
                            tr += '<th class="sorting">库存</th>'
                            tr += '<th class="sorting">是否启用</th>'
                            tr += '<th class="sorting">是否默认</th>'

                            tr += '</tr>'

                            for (var i = 0; i < arr.length; i++) {

                                tr += '<tr>'

                                var js = JSON.stringify(arr[i].att)

                                var a = js.indexOf(":")

                                if (js.search(",") != -1) {

                                    var dh = js.indexOf(",")

                                    tr += '<td>' + js.substring(a + 2, dh - 1) + '</td>'

                                    var b = js.lastIndexOf(":")

                                    tr += '<td>' + js.substring(b + 2, js.length - 2) + '</td>'

                                } else {

                                    tr += '<td>' + js.substring(a + 2, js.length - 2) + '</td>'
                                }

                                tr += '<td><input class="form-control"  placeholder="价格"></td>'
                                tr += '<td><input class="form-control" placeholder="库存数量"></td>'
                                tr += '<td><input type="checkbox" ></td>'
                                tr += '<td><input type="checkbox" ></td>'

                                tr += '</tr>'

                            }

                            $("#dataType1").html(tr)

                        }

                    </script>
                    <!--规格-->
                    <div class="tab-pane" id="spec">
                        <div class="row data-type">
                            <div class="col-md-2 title">是否启用规格</div>
                            <div class="col-md-10 data">
                                <input id="check" type="checkbox" value="1" onclick="specification()">
                            </div>
                        </div>
                        <p>

                        <div>

                            <div class="row data-type" id="dataType">

                            </div>


                            <div class="row data-type">
                                <form>
                                    <table class="table table-bordered table-striped table-hover dataTable"
                                           id="dataType1">


                                    </table>
                                </form>
                            </div>

                        </div>
                    </div>

                </div>
                <!--tab内容/-->
                <!--表单内容/-->

            </div>

            <!--总提交-->
        </div>
        <div class="btn-toolbar list-toolbar">
            <button class="btn btn-primary" onclick="addAll()"><i class="fa fa-save"></i>保存</button>
            <button class="btn btn-default">返回列表</button>
        </div>

    </section>


    <!-- 上传窗口 -->
    <div aria-hidden="true" aria-labelledby="myModalLabel" class="modal fade" id="uploadModal" role="dialog"
         tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button aria-hidden="true" class="close" data-dismiss="modal" type="button">×</button>
                    <h3 id="myModalLabel">上传商品图片</h3>
                </div>
                <div class="modal-body">


                    <table class="table table-bordered table-striped">
                        <tr>
                            <td>颜色</td>
                            <td><input class="form-control" id="color" name="color" placeholder="颜色"></td>
                        </tr>
                        <tr>
                            <td>商品图片</td>
                            <td>
                                <table>
                                    <tr>
                                        <td>
                                            <input type="file" class="form-control" name="image" id="myFile">

                                        </td>
                                        <td>
                                            <input type="hidden" id="photo" name="url">
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>

                </div>
                <div class="modal-footer">
                    <button aria-hidden="true" class="btn btn-success" data-dismiss="modal" onclick="add()">保存</button>
                    <button aria-hidden="true" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>


    <!-- 正文区域 /-->
    <script type="text/javascript">

        var editor;
        KindEditor.ready(function (K) {
            editor = K.create('textarea[name="introduction"]', {
                allowFileManager: true
            });
        });

    </script>
</form>
</body>

</html>
<script>
    $("#myFile").fileinput({
        language: 'zh',
        uploadUrl: "/test/upload",
        showCaption: true,
        showUpload: true,
        showRemove: true,
        showClose: true,
        layoutTemplates: {
            actionDelete: ''
        },
        browseClass: 'btn btn-primary',
        allowedFileExtensions: ['jpg', 'png', 'gif', 'txt'],//限制文件上传类型
        maxFileCount: 1,//最大上传数量
        maxFileSize: 2048,//设置文件上传大小 单位kb
        enctype: "multipart/form-data"
    });
    $("#myFile").on('fileuploaded', function (event, data, previewId, index) {

        if (data.response != null) {
            $("#photo").val(data.response.data);

        }
    })

    function add() {
        var color = $("#color").val();
        var url = $("#photo").val();
        $("#tbody").append(
            '<tr><td>' + color + '</td> <td><img alt="" height="100px" src="' + url + '" width="100px"> </td> <td> <button className="btn btn-default" onclick="deleteOneTr1(this)" title="删除"type="button"><iclassName="fa fa-trash-o"></i> 删除 </button></td></tr>'
        )
    }
</script>